package com.athuahua.es.controller;

import cn.hutool.json.JSONUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.ElasticsearchIndicesClient;
import co.elastic.clients.elasticsearch.indices.PutMappingRequest;
import co.elastic.clients.json.JsonData;
import com.athuahua.es.entity.OrderInfo;
import jakarta.annotation.Resource;
import lombok.Data;
import org.eclipse.parsson.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: huahua
 * @Date: 2024/10/2 0002
 * @Time: 20:30
 * @Description:
 */

@RestController
public class TestController {

    @Resource
    private ElasticsearchClient client;

    @GetMapping("/test")
    public String search() throws IOException {
        SearchResponse<Object> search = client.search(
                r -> r.query(
                        q -> q.match(
                                m -> m.field("age").query(25)))
                , Object.class);
        System.out.println(search);


        return search.toString();
    }


    //创建索引
    @GetMapping("/createIndex")
    public String createIndex() throws IOException {
        PutMappingRequest mappingRequest =
                new PutMappingRequest.Builder().index("lglbc_java_demo")
                        .properties("order_no", builder ->
                                builder.keyword(type -> type))
                        .properties("order_time", builder ->
                                builder.date(type -> type.format("yyyy-MM-dd HH:mm:ss")))
                        .properties("good_info", type -> type.nested( //创建嵌套
                                nested -> nested
                                        .properties("good_price", builder ->
                                                builder.double_(subType -> subType))
                                        .properties("good_count", builder ->
                                                builder.text(subType -> subType))
                                        .properties("good_name", builder ->
                                                builder.text(subType -> subType.fields(
                                                        "keyword", subTypeField -> subTypeField
                                                                .keyword(subSubType -> subSubType)
                                                )))))
                        .properties("buyer", builder -> builder.keyword(type -> type))
                        .properties("phone", builder -> builder.keyword(type -> type))
                        .build();
        ElasticsearchIndicesClient indices = client.indices();
        if (indices.exists(r -> r.index("lglbc_java_demo")).value()) {
            indices.delete(request -> request.index("lglbc_java_demo"));
        }
        indices.create(request -> request.index("lglbc_java_demo"));
        indices.putMapping(mappingRequest);
        return null;

    }

    //新增文档
    @GetMapping("/addDocument")
    public String addDocument() throws IOException {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo("1001");
        orderInfo.setOrderTime(new Date());
        orderInfo.setBuyer("huahua");
        orderInfo.setPhone("1234567");

        ArrayList<OrderInfo.GoodInfo> goodInfos = new ArrayList<>();
        goodInfos.add(new OrderInfo.GoodInfo(10.0, "apple", 10));
        goodInfos.add(new OrderInfo.GoodInfo(20.0, "banana", 20));
        orderInfo.setGoodInfo(goodInfos);


        Result result = client.create(
                req -> req.index("lglbc_java_demo")
                        .id("1002")
                        .document(orderInfo)
        ).result();


        return result.toString();
    }

    //更新文档
    @GetMapping("/updateDocument")
    public void updateDocument() throws IOException {
        client.updateByQuery(
                req -> req.index("lglbc_java_demo")
                        .query(q -> q.term(t -> t.field("order_no").value("1001")))
                        .script(s -> s.inline(i -> i.lang("painless")
                                .source("ctx._source['buyer']='谁能告诉我这是个什么玩意？'")))
        );

    }

    //查询文档
    @GetMapping("/searchDocument")
    public String searchDocument() throws IOException {
        SearchRequest searchRequest = SearchRequest.of(
                i -> i.index("lglbc_java_demo")
                        .query(q -> q.term(
                                t -> t.field("order_no").value("1001")
                        )));
        SearchResponse<Object> search = client.search(searchRequest, Object.class);
        System.out.println(search.toString());
        List<Hit<Object>> hits = search.hits().hits();
        for (Hit hit : hits) {
            System.out.println(hit.source().toString());
        }


        return null;
    }
}
